﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SDT.Admin.ViewModels;
using SDT.Model;
using System.Linq.Dynamic;
using SDT.Lib.Common;
using SDT.Lib.Helpers;
using SDT.Lib.Paging;
namespace SDT.Admin.Controllers
{
    [RoleHelper(Roles = RoleSystem.Administrator)]
    public class MemberController : Controller
    {
        //
        // GET: /Member/
        SDTDataContext eDataContext = new SDTDataContext();
        public ActionResult Index(int? page)
        {
            if (page == null)
                page = 1;
            page = page - 1;
            int pageSize = int.Parse(UserState.getUserStateFromRequest("member.pageSize", "PageSize", 20).ToString());
            MemberIndexModels l = new MemberIndexModels();
            var users = eDataContext.aspnet_Memberships
                        .Distinct()
                        .OrderBy(e=>e.aspnet_User.UserName)
                        .ToList();
            var lm = new List<MemberObjInfo>();
            foreach (var item in users) {
                var obj = new MemberObjInfo();
                obj.FullName = item.aspnet_User.UserName;
                obj.User = item;
                obj.ProductCount = eDataContext.Products.Where(e => e.AddBy == item.UserId).ToList().Count;
                if(obj.ProductCount>0)
                lm.Add(obj);
            }
            l.Members = lm.ToPagedList(page.Value, pageSize);
            return View(l);
        }
        public ActionResult Details(Guid id,int? page)
        {
            if (page == null)
                page = 1;
            page = page - 1;
            string order = UserState.getUserStateFromRequest("product.order", "order", "ID").ToString();
            string orderDir = UserState.getUserStateFromRequest("product.orderDir", "orderDir", "desc").ToString();
            ViewData["orderDir"] = orderDir;
            ViewData["order"] = order;
            int pageSize = int.Parse(UserState.getUserStateFromRequest("memberDetails.pageSize", "PageSize", 20).ToString());
            MemberObjInfo m = new MemberObjInfo();
            m.User = eDataContext.aspnet_Memberships.Where(e => e.UserId == id).SingleOrDefault();
            m.FullName=m.User!=null? m.User.aspnet_User.UserName:string.Empty;
            m.Products=eDataContext.Products.Where(e => e.AddBy == id)
                .OrderBy(string.Format("{0} {1}", order, orderDir))
                .ToPagedList(page.Value, pageSize);
            return View(m);
        }
    }
}
